const { server, close } = require('./test-server');
const { spawn } = require('child_process');
const path = require('path');

// 启动测试服务器
const PORT = process.env.TEST_SERVER_PORT || 3000;
server.listen(PORT, async () => {
  console.log(`Test server started on port ${PORT}`);

  try {
    // 运行测试
    const testProcess = spawn(
      'node',
      [
        '--test',
        '--test-reporter',
        'spec',
        '--test-reporter-destination',
        'stdout',
        path.join(__dirname, 'recorder.test.js'),
        path.join(__dirname, 'storage.test.js'),
        path.join(__dirname, 'vscode.test.js')
      ],
      {
        stdio: 'inherit',
        env: {
          ...process.env,
          TEST_SERVER_PORT: PORT.toString()
        }
      }
    );

    testProcess.on('exit', (code) => {
      close();
      process.exit(code || 0);
    });

  } catch (error) {
    console.error('Test failed:', error);
    close();
    process.exit(1);
  }
});

// 处理异常退出
process.on('SIGINT', () => {
  close();
  process.exit(0);
});

process.on('uncaughtException', (err) => {
  console.error('Uncaught exception:', err);
  close();
  process.exit(1);
});